/*
 * @Description: 房源列表
 * @Author: Yong
 * @Date: 2021-09-23 10:35:47
 * @LastEditTime: 2021-09-26 20:45:23
 */
import React from "react"
import { Flex, Toast } from "antd-mobile"
import { List, AutoSizer, WindowScroller, InfiniteLoader } from 'react-virtualized'
import SearchHeader from '../../components/SearchHeader'
import HouseItem from '../../components/HouseItem'
import Sticky from "../../components/Sticky"
import Filter from "./components/Filter"
import NoHouse from '../../components/NoHouse'
import { getHouseList } from "../../apis/house"
import { getCurrentCity } from '../../utils/map-function'
import styles from './index.module.css'
import { BASE_URL } from "../../utils/url"

export default class HouseList extends React.Component {
    state = {
        // 列表数据
        list: [],
        // 总数据条数
        count: 0,

        isLoading: false,
    }
    label = ''
    value = ''
    filters = {}

    async componentDidMount () {
        const { label, value } = await getCurrentCity()
        this.label = label
        this.value = value
        this.searchHouseList()
    }

    // 用来获取房屋列表数据
    async searchHouseList () {
        this.setState({ isLoading: true })
        const { list, count } = await getHouseList({ cityId: this.value, ...this.filters, start: 1, end: 20 })
        Toast.info(`共找到${count}套房源`, 1, null, false)
        this.setState({
            list, count, isLoading: false
        })
    }

    /**
     * 监听筛选点击确定
     * @param {*} filters 筛选条件对象
     */
    onFilter = filters => {
        // console.log('filters:', filters)
        // 返回页面顶部
        window.scrollTo(0, 0)
        this.filters = filters
        this.searchHouseList()
    }

    // 判断列表中的每一行是否加载完成
    isRowLoaded = ({ index }) => {
        return !!this.state.list[index]
    }

    // 用来获取更多房屋列表数据
    // 注意：该方法的返回值是一个 Promise 对象，并且，这个对象应该在数据加载完成时，来调用 resolve 让Promise对象的状态变为已完成。
    loadMoreRows = async ({ startIndex, stopIndex }) => {
        const { list } = await getHouseList({ cityId: this.value, ...this.filters, start: startIndex, end: stopIndex })
        this.setState({
            list: [...this.state.list, ...list]
        })
        return Promise.resolve()
    }

    // 渲染列表
    renderList = () => {
        const { count, isLoading } = this.state
        if (count === 0 && !isLoading) {
            return (<NoHouse>没有找到房源，请您换个搜索条件吧~</NoHouse>)
        }
        return (
            <InfiniteLoader
                isRowLoaded={this.isRowLoaded}
                loadMoreRows={this.loadMoreRows}
                rowCount={count}
            >
                {({ onRowsRendered, registerChild }) => (
                    <WindowScroller>
                        {({ height, isScrolling, scrollTop }) => (
                            <AutoSizer>
                                {({ width }) => (
                                    <List
                                        onRowsRendered={onRowsRendered}
                                        ref={registerChild}
                                        autoHeight          // 设置高度为 WindowScroller 最终渲染的列表高度
                                        width={width}       // 视口的宽度
                                        height={height}     // 视口的高度
                                        rowCount={count}    // List列表项的行数
                                        rowHeight={120}     // 每一行的高度
                                        rowRenderer={this.renderHouseList} // 渲染列表项中的每一行
                                        isScrolling={isScrolling}
                                        scrollTop={scrollTop}
                                    />
                                )}
                            </AutoSizer>
                        )}
                    </WindowScroller>
                )}
            </InfiniteLoader>
        )
    }

    // 渲染每一行元素
    renderHouseList = ({ key, index, style }) => {
        const { list } = this.state
        const house = list[index]
        if (!house) {
            return (
                <div key={key} style={style}>
                    <p className={styles.loading} />
                </div>
            )
        }

        return (
            <HouseItem
                key={key}
                onClick={() => this.props.history.push(`/detail/${house.houseCode}`)}
                // 注意：该组件中应该接收 style，然后给组件元素设置样式！！！
                style={style}
                src={BASE_URL + house.houseImg}
                title={house.title}
                desc={house.desc}
                tags={house.tags}
                price={house.price}
            />
        )
    }

    render () {
        return (
            <div className={styles.root}>
                {/* 顶部搜索导航 */}
                <Flex className={styles.header}>
                    <i className="iconfont icon-back" onClick={() => this.props.history.go(-1)} />
                    <SearchHeader cityName={this.label} className={styles.searchHeader} />
                </Flex>
                {/* 筛选区域 */}
                <Sticky><Filter onFilter={this.onFilter} /></Sticky>
                {/* 房屋列表 */}
                <div className={styles.houseItems}>{this.renderList()}</div>
            </div>
        )
    }
}